package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池
 * Thread:线程
 * Pool:池子
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        //创建一个固定大小的线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(2);

        for(int i=0;i<5;i++){
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    Thread t = Thread.currentThread();//获取运行该任务的线程
                    System.out.println(t.getName()+":正在执行任务...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(t.getName()+":执行任务完毕");
                }
            };
            threadPool.execute(r);
            System.out.println("将任务交给了线程池");
        }

        //shutdown调用后，线程池不再接受新任务，等待内部所有任务执行完毕后结束
//        threadPool.shutdown();
        //shutdownNow调用后，线程池会试图中断所有线程，当所有线程结束后结束线程池
        threadPool.shutdownNow();
        System.out.println("线程池关闭了");
    }
}



